package clang.ir;

import fixedpoint.DataflowException;

public class Add extends Operator {

    public Add() {
        child = new Node[2];
    }

    @Override
    public String getRuntimeExpression() throws DataflowException {
        for (int i = 0; i < child.length; i++) {
            // this = a - b

            Node b = child[i];
            final int aIndex = 2 - i - 1;

            // case change sign
            if (b instanceof ChangeSign) {
                // get b child runtimeExpression
                Node bChild = ((ChangeSign) b).child[0];
                String bChildRuntimeValue = bChild.getRuntimeValueWithWrap();

                // get a runtimeExpression
                Node a = child[aIndex];
                String aRuntimeValue = a.getRuntimeValueWithWrap();

                return aRuntimeValue + " - " + bChildRuntimeValue;
            } else {
                // case negative constant
                if (b instanceof ConstIntegerLiteral) {
                    final long value = ((ConstIntegerLiteral) b).getValue();
                    if (value < 0) {
                        // get a runtimeExpression
                        Node a = child[aIndex];
                        String aRuntimeValue = a.getRuntimeValueWithWrap();

                        return aRuntimeValue + " - " + toCLangIntegerLiteral(-value);
                    }
                }
            }
        }

        // the general case
        String[] runtimeValue = new String[child.length];
        String result = "";
        for (int i = 0; i < child.length; i++) {
            runtimeValue[i] = child[i].getRuntimeValueWithWrap();

            result += runtimeValue[i];
            if (i < child.length - 1) {
                result += " + ";
            }
        }
        return result;
    }
}
